/*
* 菜单模块
 * @Author: ljb
 * @Date: 2018-03-26 10:27:10
 * @Last Modified by: ljb
 * @Last Modified time: 2019-03-15 14:13:04
 */

/* eslint-disable import/extensions,import/no-unresolved */
import panxMenus from 'src/views/admin/menus';
import customerMenus from 'src/views/customer/menus';
import storeMenus from 'src/views/store/menus';
import router from 'src/router';
import { $t } from 'src/i18n';
// 交集 @see https://www.npmjs.com/package/lodash.intersection
import intersection from 'lodash.intersection';
/* eslint-enable import/extensions,import/no-unresolved */
// 2018-07-20 补充
import getUserInfo from './userToken';

const user_type = sessionStorage.getItem('user_type');

const menu_title = sessionStorage.getItem('menu_title');

let menu = [];

try {
	menu = JSON.parse(sessionStorage.getItem('menu'));
} catch (error) {
	menu = [];
}

const selected_menu = sessionStorage.getItem('selected_menu') || '';

const previous_page = sessionStorage.getItem('previous_page') || '';

let opened_menu = [];
try {
	opened_menu = JSON.parse(sessionStorage.getItem('opened_menu'));
} catch (error) {
	opened_menu = [];
}

let cachepage = [];
try {
	cachepage = JSON.parse(sessionStorage.getItem('cachepage'));
} catch (error) {
	cachepage = [];
}

/**
 *  排除与角色不符的菜单 (菜单 can_access_roles 属性中没有当前用户角色)
 * @param {array} menus 菜单配置
 * @param {array} user_roles 当前用户的角色
 */
function excludeCanNotAccessMenus(menus, user_roles) {
	let filterData = menus;
	// 非符合定制需求的customer_id不显示公司信息管理菜单
	if (!getUserInfo.state.user_info.has_company_manage_module) {
		filterData = menus.filter(err => String(err.text) !== $t('menus.company_management'));
	}
	// 非有赞用户不显示菜单
	if (Number(getUserInfo.state.user_info.has_youzan) === 0) {
		filterData = filterData.filter(err => String(err.text) !== $t('menus.youzan_management'));
	}
	const target_menus = [];
	filterData.forEach((item) => {
		const roles_intersection = intersection(item.can_access_roles, user_roles);// 取交集
		if (roles_intersection.length > 0) {
			const menu_item = {
				name: item.name,
				icon: item.icon,
				text: item.text,
				key: item.key,
			};
			if (Array.isArray(item.submenus) && item.submenus.length > 0) {
				menu_item.submenus = excludeCanNotAccessMenus(item.submenus, user_roles);
			}
			target_menus.push(menu_item);
		}
	});
	return target_menus;
}

/**
 * 获取商品管理菜单组,且移除共享商品库管理子菜单
 * @param {Array} menus
 * @param {Array} VirtualProviderMenus
 */
function takeVirtualProviderMenus(menus) {
	const [product_menu] = menus.filter(item => item.key === 'customer-product-management');
	if (product_menu && product_menu.submenus.length > 0) {
		const new_product_menus = Object.assign({}, product_menu, {
			submenus: product_menu.submenus.filter(item => item.key !== 'customer-share-product'),
		});
		return [new_product_menus];
	}
	return [];
}

/**
 * 排除不能访问的 发型素材菜单
 * @param {*} source_menus
 * @param {*} has_hair
 */
function excludeCanNotAccessHairMenu(source_menus, has_hair) {
	return source_menus.filter((item) => { // 不是 customer-hair-assets 或者(是 customer-hair-assets 且 has_hair === 1)
		const is_hair_assets = item.key === 'customer-hair-assets';
		return !is_hair_assets || has_hair;
	});
}

/**
 * 获取用户角色列表
 * @param {Object} context - store 上下文对象
 */
function getUserRoles(context) {
	const user_roles_info = context.rootGetters['userToken/getUserRoles'];
	return user_roles_info.map(info => info.const);
}


export default {

	namespaced: true,

	state: {

		user_type, // 权限

		menu_title, // 菜单顶部的说明

		side_menus: menu,

		opened_menu, // 设置当前展开的子菜单name

		selected_menu,

		previous_page,

		cachepage,
	},

	mutations: {
		/* eslint-disable no-param-reassign,no-shadow */
		setMenus(state, { user_type, side_menus, side_menu_title }) {
			state.side_menus = side_menus;
			state.menu_title = side_menu_title;
			state.user_type = user_type;

			sessionStorage.setItem('menu', JSON.stringify(side_menus));

			sessionStorage.setItem('menu_title', side_menu_title);

			sessionStorage.setItem('user_type', user_type);
		},

		/**
		 * 设置缓存
		 * @param {object} state
		 * @param {*} param.page.name path
		 */
		setCachepage(state, { page, previous_page }) {
			const cachepages = state.cachepage;

			state.selected_menu = page ? page.name : '';

			state.previous_page = previous_page ? previous_page.name : '/mirror/';

			if (!cachepages.some(cachepage => cachepage.name === page.name)) {
				state.cachepage.push(page);

				sessionStorage.setItem('cachepage', JSON.stringify(state.cachepage));
			}
			sessionStorage.setItem('previous_page', previous_page.name);

			sessionStorage.setItem('selected_menu', page.name);
		},

		deleteCachepage(state, index) {
			if (state.cachepage[index].name === state.selected_menu) {
				state.selected_menu = state.cachepage[index - 1].name;

				sessionStorage.setItem('selected_menu', state.selected_menu);

				router.push({
					path: state.cachepage[index - 1].name,
				});
			}

			state.cachepage.splice(index, 1);

			sessionStorage.setItem('cachepage', JSON.stringify(state.cachepage));
		},
		setOpenSubmenu(state, menu) {
			state.opened_menu = menu;

			sessionStorage.setItem('opened_menu', JSON.stringify(menu));
		},
		clearCache(state) {
			state.cachepage = [];

			state.menu_title = '';

			state.selected_menu = '';

			state.opened_menu = [];

			sessionStorage.clear();
		},
		/* eslint-enable no-param-reassign,no-shadow */
	},
	actions: {
		/* eslint-disable no-param-reassign,no-shadow */
		/**
		 *  解析菜单
		 * @param {*} context
		 * @param {string} payload.user_type
		 * @param {array} payload.user_roles
		 */
		resolveMenusAction(context) { // { user_type, user_roles }
			let side_menus = [];
			let side_menu_title = '';
			const user_type = context.rootGetters['userToken/getUserType'];
			// const { user_type } = context.state; debugger
			const { has_hair } = context.rootGetters['userToken/getUserInfo'];
			const is_virtual_provider = context.rootGetters['userToken/isVirtualProvider']; // 虚拟供应商类型
			const user_roles = getUserRoles(context);
			switch (user_type) {
			case 'customer':
				side_menu_title = $t('common.customer_title');
				if (is_virtual_provider) { // 虚拟供应商
					side_menus = takeVirtualProviderMenus(customerMenus);
				} else {
					side_menus = excludeCanNotAccessHairMenu(customerMenus, (has_hair === 1));
					side_menus = excludeCanNotAccessMenus(side_menus, user_roles);
				}
				break;

			case 'store':
				side_menus = excludeCanNotAccessMenus(storeMenus, user_roles, false);
				side_menu_title = $t('common.store_title');
				break;

			default:
				side_menus = panxMenus;
				side_menu_title = $t('common.admin_title');
				break;
			}
			context.commit('setMenus', {
				side_menus,
				side_menu_title,
				user_type,
			});
		},

		/**
		 * 清除缓存页面
		 * @param {*} state
		 */
		clearCachePageAction(context) {
			context.state.cachepage = [];
			sessionStorage.setItem('cachepage', JSON.stringify([]));
			context.state.previous_page = '/mirror/';
			sessionStorage.setItem('previous_page', '/mirror/');
			router.push({ path: context.state.selected_menu });
		},
		/* eslint-enable no-param-reassign,no-shadow */
	},
	getters: {
		getUserType(state) {
			return state.user_type;
		},
		getMenuTitle(state) {
			return state.menu_title || $t('common.admin_title');
		},
		getMenus(state) {
			return state.side_menus || [];
		},
		getSelectedMenu(state) {
			return state.selected_menu || '';
		},
		getCachepage(state) {
			return state.cachepage || [];
		},
		getOpenedMenu(state) {
			return state.opened_menu || [];
		},
	},
};
